import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

public class SimpleHttpHandler implements HttpHandler,AutoCloseable{

    final Logger logger = LoggerFactory.getLogger(getClass());

    //构造器初始化服务
    final HttpServer httpServer ;
    final String host;
    final int port;

    public SimpleHttpHandler(String host, int port) throws IOException {
        this.host = host;
        this.port = port;
        this.httpServer = HttpServer.create(new InetSocketAddress(host, port), 0);
        this.httpServer.createContext("/", this);
        this.httpServer.start();

        logger.info("启动tomcat服务成功，对应的主机和端口为： {}:{}", host, port);
    }


    public static void main(String[] args) throws IOException {

        try(SimpleHttpHandler simpleHttpHandler = new SimpleHttpHandler("localhost", 8081)) {
            for(;;){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    break;
                }
            }

        }
        catch (Exception e)
            {
            e.printStackTrace();
        }


    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        String Method = exchange.getRequestMethod();

        URI uri = exchange.getRequestURI();

        String path = uri.getPath();

        String Query = uri.getRawQuery();

        logger.info("{}: {}?{}", Method, path, Query);

        Headers requestHeaders = exchange.getResponseHeaders();

        requestHeaders.set("Content-Type", "text/html; charset=utf-8");
        requestHeaders.set("Cache-Control", "no-cache");

        exchange.sendResponseHeaders(200, 0);

        String s = "<h1>Hello, world.</h1><p>" + LocalDateTime.now().withNano(0) + "</p>";

        try (OutputStream out = exchange.getResponseBody()) {
            out.write(s.getBytes(StandardCharsets.UTF_8));
        }
    }

    @Override
    public void close() throws Exception {
        this.httpServer.stop(4);
    }
}
